<template>
    <div class="table">
        <div class="crumbs">
            <i class="el-icon-tickets"></i>歌曲信息
        </div>
        <div class="container">
            <div class="handle-box">
                <el-input v-model="params.name" size="mini" placeholder="请输入歌曲名"
                          style="width: 160px;"></el-input>
                <el-button type="primary" size="mini" @click="getList">查询</el-button>
                <el-button type="primary" size="mini" @click="centerDialogVisible=true">添加歌曲</el-button>
                <el-button type="danger" size="mini" @click="deleteHandle()">批量删除</el-button>
            </div>
        </div>
        <el-table size="mini" border width="100px"
                  :data="tableData" @selection-change="selectionChangeHandle">
            <el-table-column
                    type="selection"
                    width="55">
            </el-table-column>
            <el-table-column label="歌曲图片" width="110" align="center">
                <template slot-scope="scope">
                    <div class="song-img">
                        <img :src="getUrl(scope.row.pic)"
                             style="width: 100%" alt="歌曲图片">
                    </div>
                    <div class="play" @click="setSongUrl(scope.row.url,scope.row.name)">
                        <div v-if="toggle === scope.row.name">
                            <span class="icon el-icon-video-pause"></span>
                        </div>
                        <div v-if="toggle !== scope.row.name">
                            <span class="icon el-icon-video-play"></span>

                        </div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="name" label="歌手-歌名" width="120px" align="center"></el-table-column>
            <el-table-column prop="introduction" label="专辑" width="150px"></el-table-column>
            <el-table-column label="歌词">
                <template slot-scope="scope">
                    <ul class="lyric">
                        <li v-for="(item,index) in parseLyric(scope.row.lyric)" :key="index">
                            {{item}}
                        </li>
                    </ul>
                </template>
            </el-table-column>
            <el-table-column label="资源更新" align="center" width="100">
                <template slot-scope="scope">
                    <el-upload :action="uploadUrl(scope.row.id)" :before-upload="handleAvatarUpload"
                               :on-success="handleAvatarSuccess"
                               :show-file-list="false">
                        <el-button size="mini">更新图片</el-button>
                    </el-upload>
                    <br/>
                    <el-upload :action="uploadSongUrl(scope.row.id)" :before-upload="beforeSongUpload"
                               :on-success="handleSongSuccess"
                               :show-file-list="false">
                        <el-button size="mini">更新歌曲</el-button>
                    </el-upload>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="250px" align="center">
                <template slot-scope="scope">
                    <el-button size="mini" @click="editHandle(scope.row.id)">编辑</el-button>
                    <el-button size="mini" @click="deleteHandle(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
                @size-change="sizeChangeHandle"
                @current-change="currentChangeHandle"
                :current-page="params.currPage"
                :page-sizes="[5, 10, 50, 100]"
                :page-size="params.pageSize"
                :total="params.totalCount"
                layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>
        <el-dialog :title="form.id?'修改':'添加歌曲'" :visible="centerDialogVisible" center width="400px"
                   @close="closeDialog" >
            <el-form :model="form" ref="formRef" label-width="80px"
                     action="" id="tf">
                <el-form-item prop="name" label="歌曲名" size="mini">
                    <el-input type="text" name="name" v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item prop="introduction" label="专辑" size="mini">
                    <el-input type="text" name="introduction" v-model="form.introduction"></el-input>
                </el-form-item>
                <el-form-item prop="lyric" label="歌词" size="mini">
                    <el-input type="textarea" name="lyric" v-model="form.lyric"></el-input>
                </el-form-item>
                <el-form-item v-if="!form.id" prop="file" label="歌曲上传" size="mini">
                    <input type="file" name="file"/>
                </el-form-item>
            </el-form>
            <span slot="footer">
                <el-button size="mini" @click="closeDialog">取消</el-button>
                <el-button size="mini" @click="addOrUpdate">确定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import {mixin} from '../mixins/index'
    import {mapGetters} from 'vuex'
    import '../assets/font/iconfont.css'
    import {deleteSong, getSongInfo, getSongList, updateSongInfo} from '../api/index'

    export default {
        mixins: [mixin],
        data() {
            return {
                centerDialogVisible: false,
                singerId: '',
                singerName: '',
                form: {
                    id: '',
                    name: '',
                    lyric: '',
                    introduction: ''
                },
                tableData: [],
                params: {
                    currPage: 1,     //当前页
                    pageSize: 5,   //每页大小
                    totalCount: 1,//总记录数
                    isPage: true, //开启分页
                    name: ''
                },
                dataListSelections: [],
                toggle: ''
            }
        },
        computed: {
            ...mapGetters(['isPlay'])
        },
        methods: {
            getList() {
                let params = {
                    'isPage': this.params.isPage,
                    'name': this.params.name,
                    'page': this.params.currPage,
                    'limit': this.params.pageSize,
                    'singerId': this.singerId
                }
                getSongList(params).then(({data: res}) => {
                    this.tableData = res.data.list
                    this.params.totalCount = res.data.totalCount
                })
            },
            closeDialog() {
                this.centerDialogVisible = false
                // this.$refs.formRef.resetFields()
                //表单项中没有id无法进行
                this.form = {}
            },
            addOrUpdate() {
                if (this.form.id) {
                    this.updateSongInfo()
                } else {
                    this.addSong()
                }
            },
            //修改歌曲信息 不修改歌曲
            updateSongInfo() {
                updateSongInfo(this.form).then(({data: res}) => {
                    if (res.code === 0) {
                        this.getList()
                        this.closeDialog()
                        this.$message.success('修改成功')
                    } else {
                        this.$message.error('修改失败')
                    }
                })

            },
            //添加歌曲 包含歌曲信息和歌曲
            addSong() {
                let _this = this
                var form = new FormData(document.getElementById('tf'))
                form.append('singerId', this.singerId)
                form.set('name', this.singerName + '-' + form.get('name'))
                if (!form.get('lyric')) {
                    form.set('lyric', '[00:00:00]暂无歌词')
                }
                var req = new XMLHttpRequest()
                //发送请求并获取响应
                req.onreadystatechange = function () {
                    //返回完整数据 &&返回状态吗200
                    if (req.readyState === 4 && req.status) {
                        let res = JSON.parse(req.response)
                        if (res.code === 0) {
                            _this.getList()
                            _this.$refs.formRef.resetFields()
                            _this.$message.success('添加成功')
                        } else {
                            _this.$message.error('保存失败')
                        }
                    }
                }
                req.open('post', `${_this.$store.state.HOST}/song/add`, false)
                req.send(form)
                _this.closeDialog()
            },
            uploadUrl(id) {
                //从Vuex中获取图片上传的服务器ip
                return `${this.$store.state.HOST}/song/updateSongPic?id=${id}`
            },
            handleAvatarSuccess(res, file) {
                if (res.code === 0) {
                    this.getList()
                    this.notify('上传成功', 'success')
                } else {
                    this.notify('上传失败', 'error')
                }
            },
            handleAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
                if (!isJPG) {
                    this.$message.error('上次头像图片只能是jpg或png格式')
                    return false
                }
                const isLt2M = file.size / 1024 / 1024 < 2
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!')
                    return false
                }
                return isJPG && isLt2M
            },
            editHandle(id) {
                getSongInfo(id).then(({data: res}) => {
                        if (res.code === 0) {
                            this.form = res.info
                            this.centerDialogVisible = true
                        } else {
                            this.$message.error('请稍后重试')
                        }
                    }
                )
            },
            deleteHandle(id) {
                console.log(id)
                let ids = id ? [id] : this.dataListSelections.map(item => {
                    return item.id
                })
                this.$confirm(`确定对进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    const {data: res} = await deleteSong(ids)
                    if (res.code === 0) {
                        this.getList()
                        this.$message.success('删除成功')
                    } else {
                        return this.$message.error('删除失败')
                    }
                }).catch(() => {
                    this.$message.warning('取消删除')
                })
            },
            // 多选值更新
            selectionChangeHandle(val) {
                this.dataListSelections = val
            },
            //每页大小修改触发
            sizeChangeHandle(val) {
                this.params.pageSize = val
                this.params.currPage = 1
                this.getList()
            },
            //当前页修改触发
            currentChangeHandle(val) {
                this.params.currPage = val
                this.getList()
            },
            //打开编辑框
            songEdit(id, name) {
                this.$router.push({path: '/Song', query: {id, name}})
            },
            //解析歌词
            parseLyric(text) {
                let lines = text.split('\n')
                //\d 代表数字 {}代表几个字符 . 任意单字符 ()子正则表达式
                let pattern = /\[\d{2}:\d{2}.(\d{3}|\d{2})]/g
                let result = []
                for (let item of lines) {
                    let value = item.replace(pattern, '')
                    result.push(value)
                }
                return result
            },
            //上传歌曲之前的校验
            beforeSongUpload(file) {
                let testMsg = file.name.substring(file.name.lastIndexOf('.') + 1)
                if (testMsg !== 'mp3') {
                    this.$message({
                        message: '上传文件只能是mp3格式',
                        type: 'error'
                    })
                    return false
                }
                return true
            },
            //上传歌曲成功之后要做的工作
            handleSongSuccess(res) {
                if (res.code === 0) {
                    this.getList()
                    this.$message.success('上传成功')
                } else {
                    this.$message.error('上传失败')
                }
            },
            //更新歌曲url
            uploadSongUrl(id) {
                return `${this.$store.state.HOST}/song/updateSongUrl?id=${id}`
            },
            setSongUrl(url, name) {
                // 触发的是当前歌曲
                if (name === this.toggle) {
                    this.toggle = ''
                    //切换歌曲状态
                    this.$store.commit('setIsPlay', !this.isPlay)
                } else {
                    //设置当前播放音乐状态
                    this.toggle = name
                    //更换歌曲url
                    this.$store.commit('setUrl', url)
                    this.$store.commit('setIsPlay', true)
                }

            }
        },
        created() {
            this.singerId = this.$route.query.id
            this.singerName = this.$route.query.name
            this.getList()
        }
    }
</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }

    .song-img {
        width: 100%;
        height: 100%;
        border-radius: 5px;
        margin-bottom: 5px;
        overflow: hidden;
    }

    .lyric {
        height: 100px;
        overflow-y: scroll;
        overflow-x: hidden;
    }

    /*隐藏滚动条*/
    .lyric::-webkit-scrollbar {
        display: none;
    }

    .play {
        position: absolute;
        z-index: 100;
        width: 80px;
        height: 80px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        top: 18px;
        left: 15px;
    }

    .icon {
        /*width: 4em;*/
        /*height: 3em;*/
        border-color: red;
        font-size: 30px !important;
        color: white;
        fill: currentColor;
        overflow: hidden;
    }
</style>